﻿using ByHand.Model;
using ByHand.Services.Code;
using ByHand.Services.Interfaces;
using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using ByHand.Services.Implements;
using System.Collections.Generic;

namespace FrontEnd.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        private readonly IProductService _ProductService;

        private readonly IProviderService _ProviderService;
        private readonly IProductOptionService _ProductOptionService;
        private readonly IUserService _UserService;
        private readonly ILogService _LogService;

        public HomeController(IProductService ProductService, IProviderService ProviderService, IProductOptionService ProductOptionService, IUserService UserService, ILogService LogService)
        {
            _ProductService = ProductService;
            _ProviderService = ProviderService;
            _ProductOptionService = ProductOptionService;
            _UserService = UserService;
            _LogService = LogService;
        }

        public ActionResult Index(string refid, string id, string tempId, string reflocation)
        {
            if (!string.IsNullOrWhiteSpace(refid))
            {
                HttpCookie cookie = new HttpCookie("byhandrefid");
                cookie.Value = refid;
                this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
                HttpCookie cookie2 = new HttpCookie("enablepopup");
                cookie2.Value = Convert.ToString(true);
                this.ControllerContext.HttpContext.Response.Cookies.Add(cookie2);
                var userlog = "";
                if (User.Identity.IsAuthenticated) userlog = User.Identity.Name;
                var isbuttonshared = (!string.IsNullOrWhiteSpace(reflocation));
                var log = new Log()
                {
                    OrderID = 0,
                    ProductID = Convert.ToInt32(id),
                    Location = isbuttonshared ? reflocation : Request.UrlReferrer.ToString(),
                    UserType = "Nặc danh",
                    ByHandName = userlog,
                    DateTime = DateTime.Now,
                    RefID = refid
                };
                if (string.IsNullOrWhiteSpace(tempId))
                {
                    tempId = Utility.GenerateId();
                    log.ActionType = (int)ELogActionType.Link_Click;
                    log.ActionDetail = (int)ELogActionDetail.None;
                    log.UserName = tempId;
                }
                else
                {
                    log.ActionType = (int)ELogActionType.Button_Frame_Click;
                    log.ActionDetail = (int)ELogActionDetail.None;
                    log.UserName = tempId;
                }
                _LogService.Add(log);
                HttpCookie cookie4 = new HttpCookie("previouslocation");
                cookie4.Value = log.Location;
                this.ControllerContext.HttpContext.Response.Cookies.Add(cookie4);

                HttpCookie cookie3 = new HttpCookie("tempId");
                cookie3.Value = tempId;
                this.ControllerContext.HttpContext.Response.Cookies.Add(cookie3);

                return RedirectPermanent("/Home/Index");
            }
            var cookierefid = Request.Cookies["byhandrefid"];
            var refidvalue = "0";
            if (cookierefid != null)
            {
                refidvalue = cookierefid.Value;
            }
            else
            {
                HttpCookie cookie = new HttpCookie("byhandrefid");
                cookie.Value = refidvalue;
                this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
            }
            var isenablepopup = Request.Cookies["enablepopup"];
            if (isenablepopup != null && Convert.ToBoolean(isenablepopup.Value))
            {
                ViewData["callpopup"] = "true";
                Response.Cookies["enablepopup"].Value = Convert.ToString(false);
            }
            var temID = Request.Cookies["tempId"];
            if (temID != null)
            {
                ViewData["tempId"] = temID.Value;
                if (string.IsNullOrWhiteSpace(temID.Value) || temID.Value.Equals("0"))
                {
                    ViewData["tempId"] = Utility.GenerateId();
                }
            }
            var p = _ProductService.GetActive();
            p.Provider = _ProviderService.GetById(p.ProviderID);
            ViewData["options"] = _ProductOptionService.GetByProductID(p.ID);
            //ViewData["framebtn"] = framebtn;
            ViewData["refid"] = refidvalue;
            if (TempData["ResultPayment"] != null)
            {
                ViewData["ResultPayment"] = TempData["ResultPayment"];
            }
            if (User.Identity.IsAuthenticated)
            {
                ViewData["User"] = _UserService.GetByFBID(User.Identity.Name) ?? _UserService.GetByEmail(User.Identity.Name);
                ViewData["userid"] = (_UserService.GetByFBID(User.Identity.Name) ?? _UserService.GetByEmail(User.Identity.Name)).ID;
            }
            return View(p);
        }

        public ActionResult Login(string email, string password)
        {
            var u = _UserService.Login(email, password);
            if (u != null)
            {
                FormsAuthentication.SetAuthCookie(u.Email, false);
                return Json(true);
            }
            else
            {
                return Json(false);
            }
        }

        public ActionResult SignUpFB(string fbID, string fbemail, string fbname)
        {
            if (string.IsNullOrWhiteSpace(fbID))
            {
                return Json(false);
            }
            if (string.IsNullOrWhiteSpace(fbemail))
            {
                return Json(false);
            }
            if (string.IsNullOrWhiteSpace(fbname))
            {
                return Json(false);
            }
            var user = _UserService.GetByFBID(fbID);
            if (user == null)
            {
                User u = new User()
                {
                    FBID = fbID,
                    Email = fbemail,
                    ProperName = fbname,
                    JoinedDate = DateTime.Now
                };
                _UserService.Add(u);
                user = u;
            }
            FormsAuthentication.SetAuthCookie(user.FBID ?? user.Email, false);
            return Json(user);
        }

        public ActionResult LogOut()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("index", "home");
        }
        public ActionResult UserStatistic(int userid) {
            var u = _UserService.GetByFBID(User.Identity.Name) ?? _UserService.GetByEmail(User.Identity.Name);
            ViewData["click"] = StatisticsService.CountClickByUser(u.ID);
            ViewData["order"] = StatisticsService.CountOrderByUser(u.ID);
            ViewData["totalmoney"] = StatisticsService.TotalMoneyByUser(u.ID);
            return PartialView();
        }
        public ActionResult GetRefStatistic()
        {
            var u = _UserService.GetByFBID(User.Identity.Name) ?? _UserService.GetByEmail(User.Identity.Name);
            var listDomain = StatisticsService.GetDomainByUser(u.ID);
            List<object> domainStatistic = new List<object>();
            foreach (string item in listDomain)
            {
                domainStatistic.Add(new
                {
                    click = StatisticsService.GetClickByDomain(item,u.ID),
                    order = StatisticsService.GetOrderByDomain(item,u.ID),
                    domain = item,
                    money = StatisticsService.GetMoneyByDomain(item,u.ID)
                });
            }
            return Json(new { domains = domainStatistic });
        }
        private DateTime GetFromDate(string time, out int totalDay)
        {
            var cur = DateTime.Now;
            var start = new DateTime(2013,6,1);
            int diff = 0;
            if (time == "thisweek")
            {
                diff = cur.DayOfWeek - DayOfWeek.Monday;
                if (diff < 0)
                {
                    diff += 7;
                }
            }
            switch (time)
            {
                case "thismonth": totalDay = cur.Day; return new DateTime(cur.Year, cur.Month, 1, 0, 0, 0);
                case "7day": totalDay = 7; return cur.AddDays(-6);
                case "thisweek": totalDay = diff + 1; return cur.AddDays(-1 * diff);
                case "yesterday": totalDay = 1; return cur.AddDays(-1);
                case "today": totalDay = 1; return cur;
                case "all": totalDay = (cur - start).Days; return start;
                default: totalDay = 0; return cur;
            }
        }
    }
}